package bs.app.HTTPConnection;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;

import bs.app.Client.AppPage1;
import bs.app.Client.AppPage2;
import bs.app.Client.AppPage5;
import bs.app.Client.CardPage;
import bs.app.Client.IDataListener;
import bs.app.Client.MessageInfo;
import bs.app.Client.PageManager;
import bs.app.Constant.StaticText;
import bs.app.Main.CCanvas;
import bs.app.Main.CMidlet;
import bs.app.Res.CRess;
import bs.app.Util.Action;
import bs.app.Util.Utility;
import bs.app.android.Connection;
import bs.app.android.Connector;
import bs.app.android.HttpConnection;
import bs.app.android.Image;
import bs.app.android.Static;
import bs.app.sms.SMSSender;

public class CConnection{// implements sms.ISMSListener {
	public Connection connection;
	public HttpConnection hpc = null;
	public DataInputStream dis = null;
	public InputStream iStrm = null;
	public String url;
	public String Domain;
	// //////////////////////////////////////
	public IDataListener listener;
	public int NumberImage = 0;
	public int Page = 0;
	public String[][] data;
	public String[] datamotchieu;
	public static String TempData;
	public int TotalRecord = 0;
	public String[] ImgNameServer = null;
	public String[] ImgClientHave = null;
	public String PathFoder = "";
	public String[] MarkLoadImg;
	public Vector URL;
	public int width = 30;
	public int height = 30;
	public int numberpage = 1;

	public String[][] DataListForChildrenMenu;
	public String[][] DataSearchList;
	public String[][] DataHelpList = { { "Update", "Update" },
			{ "Gửi tặng", "Gift" }, { "Push SMS", "PushSMS" },
			{ "About", "About" }, { "Website", "Website" } };
	public boolean layhostt = true;
	public boolean co = false;
	public String ThongBao = "Thông Báo";

	public Vector Link;
	public Vector links = new Vector();

	public boolean isPainting = false;
	public boolean chonmucsachkhac = false;

	public int landaumatketnoi;
	public int koclearurl = -1;

	public boolean cosubmenu = false;

	// namvn begin
	public static String sKeyUserAgent = "";
	// namnv end
//	public SMSReceiver receiveSMS;
	public static String Version = "2.1";
	private static String STM = "0";
	Vector cache = new Vector();
	Vector cacheContent = new Vector();
	public long bandwidth = 0;
        public String msisdn="";

	public CConnection() {
		landaumatketnoi = 1;
		URL = new Vector();
		Link = new Vector();
		Domain = "http://einfo.giaitri24.vn";
		try {
			//receiveSMS = new SMSReceiver(this,(MessageConnection) Connector.open("sms://:2010"));
			//receiveSMS.Start();
		} catch (Exception e) {
		}
	}
        private String getFile(String file) throws Exception {
            InputStream is = Static.getResourceAsStream(file);
            int len=0;
            byte[] _data = new byte[64];
            StringBuffer sb = new StringBuffer();
            while((len=is.read(_data))!=-1) {
                sb.append(new String(_data,0,len));
            }
            is.close();
            return sb.toString();
        }

        public String getValue(String Name){
            String result="";
            try {
                result = getFile("/app.conf");
                String[] temp=split(result.replace('\r', ' ').trim(), "\n") ;
                for (int i = 0; i < temp.length; i++) {
                    String arrValue = temp[i].trim();
                    String[] name=split(arrValue,"|");
                    if(name[0].toLowerCase().equals(Name.toLowerCase()))
                        return name[1];
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            if(result.equals("") && Name.toLowerCase().equals("host"))
                return "http://einfo.giaitri24.vn/?ctrl=ListHost";
            if(result.equals("") && Name.toLowerCase().equals("alhost"))
                return "http://3g.topteen.vn/einfo/?ctrl=ListHost";
            return result;
        }

        public void loadMSISDN(){            
            msisdn=Utility.loadRMS("msisdn");
        }
	private double getMemoryPercent() {
		double freeMem = Runtime.getRuntime().freeMemory();
		double totlMem = Runtime.getRuntime().totalMemory();
		return freeMem / totlMem;
	}

	private Image getImageFromCache(String str) {
		for (int i = 0; i < cache.size(); i++) {
			Object[] object = (Object[]) cache.elementAt(i);
			String name = object[0].toString();
			if (name.toLowerCase().equals(str.toLowerCase())) {
				return (Image) object[1];
			}
		}
		return null;
	}

	private void addImagToCache(String str, Image img) {
		if (getMemoryPercent() > 50 && cacheContent.size() > 0)
			cache.removeElementAt(0);
		Object[] object = new Object[] { str, img };
		cache.addElement(object);
	}

	private byte[] getStringFromCache(String str) {
		for (int i = 0; i < cacheContent.size(); i++) {
			Object[] object = (Object[]) cacheContent.elementAt(i);
			String name = object[0].toString();
			if (name.toLowerCase().equals(str.toLowerCase())) {
				return (byte[]) object[1];
			}
		}
		return null;
	}

	private void addStringToCache(String str, byte[] content) {
		if ((getMemoryPercent() > 50 || cacheContent.size() > 20)
				&& cacheContent.size() > 0)
			cacheContent.removeElementAt(0);
		Object[] object = new Object[] { str, content };
		cacheContent.addElement(object);
	}

	public void setURL(String url) {
		url = URLEncode(url);
		this.url = Domain + url;
	}

	public void setListenner(IDataListener lis) {
		listener = lis;
	}

	HttpHelper getdata = null;

	public void RequestServerGetData() {
		
		System.out.println("duong dan " + url);
		
		if (getdata == null) {
			getdata = new HttpHelper();
			getdata.start();
		} else
			getdata.complete = false;
	}

	ReadImage Loading = null;

	public void RequestServerGetImage() {
		if (Loading != null)
			Loading.stopAll();
		if (Loading == null) {
			Loading = new ReadImage(this);
			Loading.start();
		} else {
			Loading.Reset(this);
			Loading.complete = false;
		}
		System.gc();
	}

	public String URLEncode(String s) {
		StringBuffer sbuf = new StringBuffer();
		int ch;
		for (int i = 0; i < s.length(); i++) {
			ch = s.charAt(i);
			switch (ch) {
			case ' ': {
				sbuf.append("%20");
				break;
			}
			case '!': {
				sbuf.append("%21");
				break;
			}
			case '*': {
				sbuf.append("%2A");
				break;
			}
				// case '\'': { sbuf.append("%27"); break;}
			case '(': {
				sbuf.append("%28");
				break;
			}
			case ')': {
				sbuf.append("%29");
				break;
			}
			case ';': {
				sbuf.append("%3B");
				break;
			}
				// case ':': { sbuf.append("%3A"); break;}
			case '@': {
				sbuf.append("%40");
				break;
			}
				// case '&': { sbuf.append("%26"); break;}
				// case '=': { sbuf.append("%3D"); break;}
			case '+': {
				sbuf.append("%2B");
				break;
			}
			case '$': {
				sbuf.append("%24");
				break;
			}
			case ',': {
				sbuf.append("%2C");
				break;
			}
				// case '/': { sbuf.append("%2F"); break;}
				// case '?': { sbuf.append("%3F"); break;}
				// case '%': { sbuf.append("%25"); break;}
			case '#': {
				sbuf.append("%23");
				break;
			}
			case '[': {
				sbuf.append("%5B");
				break;
			}
			case ']': {
				sbuf.append("%5D");
				break;
			}
			default:
				sbuf.append((char) ch);
			}
		}
		return sbuf.toString();
	}

	public void RemoveURLAndLink() {
		if (koclearurl != 1) {
			if (URL.size() > 0) {
				URL.removeElementAt(URL.size() - 1);
			}
			if (Link.size() > 0 && (URL.size() == Link.size())) {
				Link.removeElementAt(Link.size() - 1);
			}
			koclearurl = -1;
		}
	}

	public MessageInfo readMessage() throws Exception {
		
		System.out.println("duong dan " + url);
		
		co = false;
		if (layhostt == true) {
			 byte[] HostData = null;
			 try {
                 HostData = getViaHttpsConnection(getValue("Host"));
                 //HostData = getViaHttpsConnection("http://einfo.giaitri24.vn/doitac/HOATRA/?ctrl=ListBD&Host=true");
                 //HostData = getViaHttpsConnection("http://einfo.giaitri24.vn/doitac/HOATRA/Itop/?ctrl=ListHost");
              } catch (Exception e) {
                  HostData = getViaHttpsConnection(getValue("ALHost"));
                  //HostData = getViaHttpsConnection("http://einfo.giaitri24.vn/doitac/HOATRA/?ctrl=ListBD&Host=true");
                  //HostData = getViaHttpsConnection("http://itop.topteen.vn/doitac/HOATRA/Itop/?ctrl=ListHost");
              }

			String Host = new String(HostData, "UTF-8");
			Domain = Host.substring(2);
			String[] ListDomain = split(Domain, PageManager.split_char20);
			for (int i = 0; i < ListDomain.length; i++) {
				try {
					Domain = ListDomain[i];url = Domain;
					byte[] HostDataTemp = getViaHttpsConnection(Domain + "/?ctrl=Connection");
					//namnv begin
					String strKey = new String(HostDataTemp,"UTF-8");
					//System.out.println("strKey:"+strKey);
					if(strKey.trim().indexOf("K:") != -1){ // user agent key
						String sTemp = strKey.substring(2);
						if(!sTemp.trim().equals(sKeyUserAgent)){	//update key						
							sKeyUserAgent =sTemp.trim();
							CMidlet.saveRMS(sKeyUserAgent);
						}
					}					
					//namnv end
					break;
				} catch (Exception ex) {
				}
			}
			layhostt = false;
		}
		byte[] dataImg = null;
		String str = "";
		if ((dataImg = getStringFromCache(url)) == null) {
			dataImg = getViaHttpsConnection(url);
			str = new String(dataImg, "UTF-8");
			if (str.length() > 2 && isNumberic(str.substring(0, 1)))
				addStringToCache(url, dataImg);
			else if (str.trim().equals(""))
				str = "R:101";
		} else
			str = new String(dataImg, "UTF-8");
		return getMessage(str);
	}

	private boolean isNumberic(String value) {
		try {
			Integer.parseInt(value.trim());
			return true;
		} catch (NumberFormatException e) {
		}
		return false;
	}

	public MessageInfo getMessage(String str) throws Exception {
		String currentpage = null;
		String data = null;
		//add 13/12/2011
		if(str.trim().substring(0, 2).equals("K:")){ // user agent key
			String sTemp = str.substring(2);
			if(!sTemp.trim().equals(sKeyUserAgent)){	//update key						
				sKeyUserAgent =sTemp.trim();
				CMidlet.saveRMS(sKeyUserAgent);
			}
		}else if(str.trim().substring(0, 2).equals("C:")){ // register card 
			CCanvas.cardPage =new CardPage();
			String[] _link = split(str.trim().substring(2).trim(),PageManager.split_char20);
			CCanvas.cardPage.init(_link);
			CCanvas.CurrentScreen= CCanvas.IsCardPage;
			co = true;
			RemoveURLAndLink();			
		}	
		else if (str.trim().equals("R:0")) // đăng ký thành công
		{
			CCanvas.s_Instan.dialog.initCommand(false, null, true, StaticText.cmdClose[CCanvas.langue], false, null);
			CCanvas.s_Instan.dialog.initValue(ThongBao, "Đăng ký thành công.");
			CCanvas.CurrentScreen = CCanvas.isDialog;
			co = true;
			RemoveURLAndLink();
		} else if (str.trim().equals("R:101")) // Lỗi hệ thống
		{
			CCanvas.s_Instan.dialog.initCommand(false, null, true,StaticText.cmdClose[CCanvas.langue], false, null);
			CCanvas.s_Instan.dialog.initValue(ThongBao, "Lỗi hệ thống.");
			CCanvas.CurrentScreen = CCanvas.isDialog;
			co = true;
			RemoveURLAndLink();
		} else if (str.trim().equals("R:102")) // không tìm thấy dữ liệu
		{
			CCanvas.s_Instan.dialog.initCommand(false, null, true, StaticText.cmdClose[CCanvas.langue], false, null);
			CCanvas.s_Instan.dialog.initValue(ThongBao, "Không tìm thấy dữ liệu.");
			CCanvas.CurrentScreen = CCanvas.isDialog;
			co = true;
			RemoveURLAndLink();
		} else if (str.trim().equals("R:103")) // hệ thống đang xây dựng
		{
			CCanvas.s_Instan.dialog.initCommand(false, null, true, StaticText.cmdClose[CCanvas.langue], false, null);
			CCanvas.s_Instan.dialog.initValue(ThongBao, "Hệ thống đang xây dựng.");
			CCanvas.CurrentScreen = CCanvas.isDialog;
			co = true;
			RemoveURLAndLink();
		} else if (str.trim().startsWith("R:200")) // bạn có đồng ý trả 100 cho lần này ko
		{
			String[] price = split(str.substring(5).trim(), PageManager.split_char20);
			CCanvas.s_Instan.dialog.initCommand(true, StaticText.cmdOk[CCanvas.langue], false, null, true, StaticText.cmdNo[CCanvas.langue]);
			CCanvas.s_Instan.dialog.initValue(ThongBao, "Bạn có đồng ý trả " + price[0] + " đ" + " cho lần này không?");
			CCanvas.s_Instan.dialog.setcharing(true, price[1]);
			CCanvas.CurrentScreen = CCanvas.isDialog;
			co = true;
			RemoveURLAndLink();
		} else if (str.trim().equals("R:201")) // tính cước ko thành công
		{
			CCanvas.s_Instan.dialog.initCommand(false, null, true, StaticText.cmdClose[CCanvas.langue], false, null);
			CCanvas.s_Instan.dialog.initValue(ThongBao, "Tính cước không thành công.");
			CCanvas.CurrentScreen = CCanvas.isDialog;
			co = true;
			RemoveURLAndLink();
		} else if (str.trim().equals("R:203")) // ko xác định đc số thuê bao
		{
			CCanvas.s_Instan.dialog.initCommand(false, null, true, StaticText.cmdClose[CCanvas.langue], false, null);
			CCanvas.s_Instan.dialog.initValue(ThongBao, "Không xác định được số thuê bao.");
			CCanvas.CurrentScreen = CCanvas.isDialog;
			co = true;
			RemoveURLAndLink();
		} else if (str.trim().equals("R:204")) // đăng ký không thành công
		{
			CCanvas.s_Instan.dialog.initCommand(false, null, true, StaticText.cmdClose[CCanvas.langue], false, null);
			CCanvas.s_Instan.dialog.initValue(ThongBao, "Đăng ký không thành công.");
			CCanvas.CurrentScreen = CCanvas.isDialog;
			co = true;
			RemoveURLAndLink();
		} else if (str.trim().substring(0, 2).equals("B:")) // đăng ký không thành công
		{
			CCanvas.s_Instan.dialog.initCommand(false, null, true, StaticText.cmdClose[CCanvas.langue], false, null);
			CCanvas.s_Instan.dialog.initValue(ThongBao, "Bạn đã dùng hết " + (bandwidth / 1000) + "KB.");
			CCanvas.CurrentScreen = CCanvas.isDialog;
			co = true;
			RemoveURLAndLink();
		} else if (str.trim().substring(0, 2).equals("T:")) {
			String[] _link = split(str.trim().substring(2).trim(), PageManager.split_char20);
			co = true;
			if (STM.equals("0")) {
				CCanvas.s_Instan.dialog.initCommand(true, StaticText.cmdOk[CCanvas.langue], false, null, true, StaticText.cmdNo[CCanvas.langue]);
				CCanvas.s_Instan.dialog.initValue("Thông Báo", _link[1]);
				CCanvas.s_Instan.dialog.setUrl(_link[0], 0);
				CCanvas.CurrentScreen = CCanvas.isDialog;
			} else {
				CCanvas.CurrentScreen = CCanvas.SaveStatePrevious;
				links.addElement(_link[0]);
			}
			RemoveURLAndLink();
		} else if (str.trim().substring(0, 2).equals("L:")) {
			//System.out.println("str:"+ str);
			String[] _link = split(str.trim().substring(2).trim(),PageManager.split_char20);
			String _version = "";
			if (_link.length > 1)
				_version = _link[1];
			co = true;
			if (!_version.equals("") && Version.equals(_version)) {
				CCanvas.s_Instan.dialog.initCommand(false, null, true, StaticText.cmdClose[CCanvas.langue], false, null);
				CCanvas.s_Instan.dialog .initValue(ThongBao, "Không tìm thấy phiên bản mới hơn phiên bản đang dùng!");
				CCanvas.CurrentScreen = CCanvas.isDialog;
			} else {
//				if (STM.equals("0")) {
//					CCanvas.s_Instan.dialog.initCommand(true, StaticText.cmdOk[CCanvas.langue], false, null, true, StaticText.cmdNo[CCanvas.langue]);
//					CCanvas.s_Instan.dialog.initValue( "Thông Báo", "Đóng ứng dụng để download chọn \"Có\". Nếu máy bạn hỗ trợ popup chọn \"Không\"!");
//					CCanvas.s_Instan.dialog.setUrl(_link[0], 0);
//					CCanvas.CurrentScreen = CCanvas.isDialog;
//				} else {
					CCanvas.CurrentScreen = CCanvas.SaveStatePrevious;
//					if (!_version.equals("")) {
						try {
							String sLink = URLEncode(_link[0]);
							//CMidlet.instanMidlet.platformRequest(_link[0]);
							CMidlet.instanMidlet.platformRequest(sLink);
//							CMidlet.instanMidlet.exit();
						} catch (Exception e) {
						}
//					} else
//						links.addElement(_link[0]);
//				}
			}
			RemoveURLAndLink();
		} else if (str.trim().substring(0, 2).equals("M:")) {
			CCanvas.CurrentScreen = CCanvas.SaveStatePrevious;
			String[] smsdata = split(str.substring(2), PageManager.split_char20);
//			SMSManager.SMS_CENTER = smsdata[1];
//			SMSManager.sendSMSToConfirmReward(smsdata[0], smsdata[1],smsdata[2], new Action() {
//				public void perform() {
//				}
//			});
			SMSSender.sendSMSToConfirmReward(smsdata[0], smsdata[1], new Action() {
				public void perform() {
				}
			});
			if (URL.size() > Link.size())
				URL.removeElementAt(URL.size() - 1);
		} else {
			if (str.trim().substring(0, 2).equals("I:")) {
				byte[] dataImg = null;
				setURL(str.trim().substring(2));
				if ((dataImg = getStringFromCache(url)) == null) {
					dataImg = getViaHttpsConnection(url);
					str = new String(dataImg, "UTF-8");
					String Header = "";
					if (str.length() > 2)
						Header = str.trim().substring(0, 2);
					if (isNumberic(Header))
						addStringToCache(url, dataImg);
					else if (str.trim().equals(""))
						str = "R:101";
					if (Header.startsWith("R:") || Header.startsWith("L:")
							|| Header.startsWith("S:")
							|| Header.startsWith("W:")
							|| Header.startsWith("M:")) {
						URL.addElement(url);
						Link.addElement("");
						getMessage(str);
						return null;
					}
				} else
					str = new String(dataImg, "UTF-8");
			}
			if (Loading != null)
				Loading.stopAll();

			currentpage = str.substring(0, str.indexOf(" "));
			data = str.substring(str.indexOf(" ") + 1,
					str.length() - str.indexOf(" ") + 1);
			co = false;
			if (cosubmenu == true && Integer.parseInt(currentpage.trim()) == 1) {
				CCanvas.s_Instan.connect.URL.removeAllElements();
				CCanvas.s_Instan.connect.Link.removeAllElements();
				CCanvas.apppage1 = null;
				CCanvas.apppage2 = null;
				CCanvas.apppage5 = null;
				CCanvas.s_Instan.connect.URL.addElement("");
				cosubmenu = false;
			}
			return new MessageInfo(currentpage, data);
		}
		return null;
	}

	public void receiveData(MessageInfo msg) {
		if (msg.IdPage.trim().equals("1")) {
			listener.Page1(msg.data);
		} else if (msg.IdPage.trim().equals("2")
				|| msg.IdPage.trim().equals("3")
				|| msg.IdPage.trim().equals("4")
				|| msg.IdPage.trim().equals("6")) {
			listener.Page2_3_4_6(msg.IdPage.trim(), msg.data);
		} else if (msg.IdPage.trim().equals("5")) {
			listener.Page5(msg.data);
		}
	}

	public void receiveImage(int Page, int element, String[][] data,
			String[] datamotchieu, Image[] imgserver) {
		if (Page == 1) {
			if (CCanvas.apppage1 == null) {
				CCanvas.apppage1 = new AppPage1();
			}
			CCanvas.apppage1.init(element, data, ImgClientHave, imgserver, MarkLoadImg);
			CCanvas.CurrentScreen = CCanvas.AppPage1;
			CRess.ClearLogo();
			CCanvas.splash = null;
			CCanvas.apppage2 = null;
			resetdata();
			System.gc();
		} else if (Page == 2 || Page == 3 || Page == 4 || Page == 6) {
			if (CCanvas.apppage2 == null) {
				CCanvas.apppage2 = new AppPage2(element);
			}
			CCanvas.apppage2.Page = Page;
			CCanvas.apppage2.NumberPage = numberpage;
			CCanvas.apppage2.init(element, data, imgserver);
			CCanvas.CurrentScreen = CCanvas.AppPage2_3_4_6;
			resetdata();
			CCanvas.apppage1 = null;
			CCanvas.s_Instan.apppage5 = null;
			System.gc();
		} else if (Page == 5) {
			if (CCanvas.apppage5 == null) {
				CCanvas.apppage5 = new AppPage5();
			}
			CCanvas.apppage5.init(datamotchieu, imgserver);
			CCanvas.CurrentScreen = CCanvas.AppPage5;
			CCanvas.apppage2 = null;
			resetdata();
			System.gc();
		}
	}

	public void resetdata() {
		hpc = null;
		dis = null;
		NumberImage = 0;
		Page = 0;
		data = null;
		datamotchieu = null;
		TotalRecord = 0;
		ImgNameServer = null;
		ImgClientHave = null;
		PathFoder = "";
		MarkLoadImg = null;
		System.gc();
	}

	public static String[] split(String original, String separator) {
		Vector nodes = new Vector();
		int index = original.indexOf(separator);
		while (index >= 0) {
			nodes.addElement(original.substring(0, index));
			original = original.substring(index + separator.length());
			index = original.indexOf(separator);
		}
		// Get the last node
		nodes.addElement(original);
		// Create splitted string array
		String[] result = new String[nodes.size()];
		if (nodes.size() > 0) {
			for (int loop = 0; loop < nodes.size(); loop++) {
				result[loop] = (String) nodes.elementAt(loop);

			}
		}
		return result;
	}

	// ///////////////////////////////// http connection from sun developer
	public byte[] getViaHttpsConnection(String url) throws IOException {
		if (url.indexOf("/?") == -1)
			url += "/";

		HttpConnection c = null;
		int rc;
		// String respBody = new String(""); // return empty string on bad
		// things
		// TODO -- better way to handle unexpected responses
		byte[] data = null;
		try {
			c = (HttpConnection) Connector.open(url, Connector.READ);
			//TODO:
			c.setRequestMethod(HttpConnection.GET);
			c.setRequestProperty("User-Agent", sKeyUserAgent + ";android STM/" + STM + "-" + Version + "-" + bandwidth);
//			 c.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0 STM/"+STM + "-"+ Version + "-" + bandwidth);
			c.setRequestProperty("Cache-Control", "no-store");
			c.setRequestProperty("Connection", "close"); // not sure this is a good idea, but HTTP/1.0 might be
															// less error-prone, some clients have trouble with chunked responses

			// Getting the response code will open the connection,
			// send the request, and read the HTTP response headers.
			// The headers are stored until requested.
//			rc = c.getResponseCode();

			// Get the length and process the data
//			int len = c.getHeaderFieldInt("Content-Length", 0);

			data = readFromHTTPConnection(c);

			bandwidth += data.length;
			// respBody=new String(data);
		} catch (ClassCastException e) {
			throw new IllegalArgumentException("Not an HTTP URL");
		} finally {
			if (c != null)
				c.close();
		}
//		if (rc != HttpConnection.HTTP_OK) {
//
//		}
//		//System.out.println("data:"+data);
		return data;
	}

	/*
	 * Copied from : http://developers.sun.com/mobility/midp/questions/calcbyte/
	 */
	private byte[] readFromHTTPConnection(HttpConnection hpc) {
		byte[] bytes;

		try {
			InputStream in = hpc.openInputStream();//Data
			int length = (int) hpc.getLength();
			if (length == -1) {
				// Reading from an HTTP 1.0 server or a chunked HTTP 1.1
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				int c;
				while (true) {
					c = in.read();
					if (c == -1)
						break;
					baos.write(c);
				}
				bytes = baos.toByteArray();
				baos.close();
				baos = null;
			} else {
				// Reading a Content-Length labeled payload
				bytes = new byte[length];
				DataInputStream dis = new DataInputStream(in);
				dis.readFully(bytes, 0, length);
				dis.close();
				dis = null;
			}
			in.close();
			in = null;
			
			//System.out.println("CONTENT="+(new String(bytes)));
			
		} catch (IOException e) {
			return null;
		}
		return bytes;
	}

	public void receiveTextSMS(final String str, String sender) {
		try {
                    String[] Link=split(str, " ");
                     if(Link.length>1 && Link[1].startsWith("L:"))
                     {                        
                        msisdn=sender;
                        Utility.saveMsisdn(msisdn);
                        RemoveURLAndLink();
                        CCanvas.s_Instan.submenu.resetColorindex();
                        CCanvas.s_Instan.LoadingState.timeForLoading=50;
                        CCanvas.s_Instan.LoadingState.time=CCanvas.s_Instan.LoadingState.fixtime;
                        CCanvas.CurrentScreen=CCanvas.isChangeLoadingState;
                        String link=Link[1].substring(2);
                        CCanvas.s_Instan.connect.URL.addElement(link);
                        CCanvas.s_Instan.connect.Link.addElement("SMS");
                        CCanvas.s_Instan.connect.setURL(link);
                        CCanvas.s_Instan.connect.RequestServerGetData();
                        return;
                     }
			MessageInfo message = getMessage(str);
			if (message != null) {
				receiveData(message);
			}
			landaumatketnoi = 3;
		} catch (Exception e) {
			if (co == false) {
				if (koclearurl != 1) {
					if (Link.size() > 0) {
						Link.removeElementAt(Link.size() - 1);
					}
					if (URL.size() > 0) {
						URL.removeElementAt(URL.size() - 1);
					}
					koclearurl = -1;
				}
				CCanvas.CurrentScreen = CCanvas.SaveStatePrevious;

			}
			if (landaumatketnoi == 1) {
				landaumatketnoi = 2;
			}
			CCanvas.s_Instan.submenu.resetColorindex();
			CCanvas.s_Instan.submenu.resetMenu();
		}
		System.gc();
	}

	public void receiveBinarySMS(byte[] data, String sender) {
		try {
			receiveTextSMS(new String(data, "UTF-8"), sender);
		} catch (Exception e) {
		}
	}

	class HttpHelper extends Thread {
		public boolean complete = false;

		public void run() {
			while (true) {
				try {
					MessageInfo message;
					// nhan phan hoi tu server
					message = readMessage();
					if (message != null) {
						receiveData(message);
					}
					
					System.out.println("respose tu servr " + message.data + "  hghjghgf " + message.IdPage);
					landaumatketnoi = 3;
				} catch (Exception e) {
					if (co == false) {
						if (koclearurl != 1) {
							if (Link.size() > 0) {
								Link.removeElementAt(Link.size() - 1);
							}
							if (URL.size() > 0) {
								URL.removeElementAt(URL.size() - 1);
							}
							koclearurl = -1;
						}
						CCanvas.CurrentScreen = CCanvas.SaveStatePrevious;

					}
					if (landaumatketnoi == 1) {
						landaumatketnoi = 2;
					}
					CCanvas.s_Instan.submenu.resetColorindex();
					CCanvas.s_Instan.submenu.resetMenu();
				}
				complete = true;
				while (complete) {
					try {
						sleep(100);
					} catch (InterruptedException e) {
					}
				}

			}
		}
	}

	class ReadImage extends Thread {
		public boolean complete = false;
		Image[] img;
		public ImageHelper imgThread = null;
		private String url = "";
		private int Page = 0;
		private int NumberImage = 0;
		private String[] ImgNameServer = null;
		private String[] ImgClientHave = null;
		private String[] MarkLoadImg = null;
		private String[][] data = null;
		private String[] datamotchieu = null;
		private String PathFoder = "";
		private int height = 0;
		private int width = 0;

		public ReadImage(CConnection connection) {
			Reset(connection);
		}

		public void Reset(CConnection connection) {
			this.url = connection.url;
			this.Page = connection.Page;
			this.ImgNameServer = connection.ImgNameServer;
			this.MarkLoadImg = connection.MarkLoadImg;
			this.PathFoder = connection.PathFoder;
			this.PathFoder = connection.PathFoder;
			this.data = connection.data;
			this.NumberImage = connection.NumberImage;
			this.datamotchieu = connection.datamotchieu;
			// this.ImgClientHave=connection.ImgClientHave;
			this.height = connection.height;
			this.width = connection.width;
		}

		public void stopAll() {
			imgThread.isStop = true;
		}

		public void setURL(String url) {
			url = URLEncode(url);
			this.url = Domain + url;
		}

		public void readImage(Image[] tempimg) throws Exception {
			if (this.Page == 1) {
				try {
					byte[] dataImg = null;
					int indexImage = 0;
					for (int i = 0; i < this.data.length; i++) {

						if (imgThread.isStop)
							return;
						if (MarkLoadImg[i].equals("1")) {
							String Path = this.PathFoder
									+ this.ImgNameServer[indexImage];
							if ((tempimg[indexImage] = getImageFromCache(Path)) == null) {
								setURL(Path);
								dataImg = getViaHttpsConnection(url);
								tempimg[indexImage] = Image.createImage(
										dataImg, 0, dataImg.length);
								addImagToCache(Path, tempimg[indexImage]);
							}
							CRess.IconApp[i / CCanvas.apppage1.colum][i
									% CCanvas.apppage1.colum] = tempimg[indexImage];
							indexImage++;
						}
					}
				} catch (Exception e) {
					CCanvas.s_Instan.dialog.initCommand(false, null, true,
							StaticText.cmdClose[CCanvas.langue], false, null);
					CCanvas.s_Instan.dialog.initValue("Thông Báo",
							"Kết nối đã bị ngắt ");
					CCanvas.CurrentScreen = CCanvas.isDialog;
				}
			} else if (this.Page == 2 || this.Page == 3 || this.Page == 4
					|| this.Page == 6) {
				int indexDetectImg = 0;
				boolean cohinhkhac = false;
				for (int i = 0; i < this.data.length; i++) {
					cohinhkhac = false;
					// ko co hinh thi lay hinh mac dinh
					if (this.data[i][2] == null
							|| this.data[i][2].trim().equals("")) {
						tempimg[i] = Image.createImage("/ma.png");
					} else // co hinh
					{
						byte[] dataImg = null;
						if (i == 0) // record dau tien ko bang "" thi load len
						{
							try {
								String temp = this.data[i][2].trim()
										+ "?height=" + this.height + "&width="
										+ this.width;
								if ((tempimg[i] = getImageFromCache(temp)) == null) {
									setURL(temp);
									dataImg = getViaHttpsConnection(this.url);
									tempimg[i] = Image.createImage(dataImg, 0,
											dataImg.length);
									addImagToCache(temp, tempimg[i]);
								}
							} catch (Exception e) {
								tempimg[i] = Image.createImage("/ma.png");
							}
						} else // record thu 2 tro di
						{
							for (int k = 0; k < i; k++) {
								if (this.data[indexDetectImg][2].trim().equals(
										this.data[k][2].trim())) {
									tempimg[indexDetectImg] = tempimg[k];
									cohinhkhac = true;
									break;
								}
							}
							if (cohinhkhac == false) // hinh dc load ko giong
														// voi nhung tam hinh
														// truoc
							{
								try {
									String temp = this.data[i][2].trim()
											+ "?height=" + this.height
											+ "&width=" + this.width;
									if ((tempimg[i] = getImageFromCache(temp)) == null) {
										setURL(temp);
										dataImg = getViaHttpsConnection(this.url);
										tempimg[i] = Image.createImage(dataImg,
												0, dataImg.length);
										addImagToCache(temp, tempimg[i]);
									}

								} catch (Exception e) {
									tempimg[i] = Image.createImage("/ma.png");
								}
							}
						}
					}
					if (imgThread.isStop)
						return;
					CRess.IconApp[i][0] = tempimg[i];
					indexDetectImg++;
				}
			} else if (this.Page == 5) {
				byte[] dataImg = null;
				for (int i = 0; i < this.ImgNameServer.length; i++) {
					try {
						String Path = this.ImgNameServer[i]+ "?height=150&width=150";
						if ((tempimg[i] = getImageFromCache(Path)) == null) {
							setURL(Path);
							dataImg = getViaHttpsConnection(this.url);
							tempimg[i] = Image.createImage(dataImg, 0,dataImg.length);
							addImagToCache(Path, tempimg[i]);
						}

					} catch (Exception e) {
						// tempimg[i]=Image.createImage("/e404.png");
						tempimg[i] = Image.createImage("/ma.png");
					}
					if (imgThread.isStop)
						return;
					CCanvas.apppage5.ImageServer[i] = tempimg[i];
				}

			}
		}

		public void run() {
			while (true) {
				try {
					if (this.Page == 2 || this.Page == 3 || this.Page == 4
							|| this.Page == 6)
						img = new Image[data.length];
					else
						img = new Image[ImgNameServer.length];
					Image tempimg = null;
					if (Page == 1)
						tempimg = Image.createImage("/item6.png");
					else
						tempimg = Image.createImage("/ma.png");
					for (int i = 0; i < img.length; i++) {
						img[i] = tempimg;
					}
					receiveImage(this.Page, this.NumberImage, this.data,
							this.datamotchieu, img);
					if (imgThread == null) {
						imgThread = new ImageHelper();
						imgThread.start();
					} else {
						imgThread.isStop = false;
						imgThread.complete = false;
					}
				} catch (Exception e) {
					CCanvas.s_Instan.dialog.initCommand(false, null, true,
							StaticText.cmdClose[CCanvas.langue], false, null);
					CCanvas.s_Instan.dialog.initValue("Thông Báo",
							"Kết nối đã bị ngắt " + e.toString());
					CCanvas.CurrentScreen = CCanvas.isDialog;
				}
				complete = true;
				while (complete) {
					try {
						while (links.size() > 0) {
							String requets = (String) links.elementAt(0);
							links.removeElementAt(0);
							CMidlet.instanMidlet.platformRequest(requets);
						}
						sleep(100);
						System.gc();
					} catch (Exception e) {
					}
				}
			}
		}

		class ImageHelper extends Thread {
			public boolean isStop = false;
			public boolean complete = false;

			public void run() {

				while (true) {
					try {
						CCanvas.ispaintBandwidth = true;
						readImage(img);
						if (Page == 5) {
							CCanvas.apppage5.ReLoadImage(img);
						}
					} catch (Exception e) {
					}
					complete = true;
					while (complete) {
						try {
							sleep(100);
							CCanvas.ispaintBandwidth = false;
						} catch (InterruptedException e) {
						}
					}
				}
			}
		}
	}
}
